<template>
    <div class="template-config">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>配置模板</span>
                </div>
            </template>

            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="template-form">
                <el-form-item label="后台网站名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入后台网站名称" clearable />
                </el-form-item>
                <el-form-item label="后台favicon" prop="web_favicon">
                    <div style="width: 100%;display: flex;flex-direction: column;">
                        <el-upload ref="logoUploadRef" class="logo-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleWebFaviconSuccess" :before-upload="beforeWebFaviconUpload" :headers="uploadHeaders">
                            <img v-if="form.web_favicon" :src="form.web_favicon" class="logo-preview" />
                            <el-icon v-else class="logo-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <div class="upload-tip">只能上传jpg/png文件，且不超过2MB</div>
                    </div>
                </el-form-item>
                <el-form-item label="后台logo" prop="web_logo">
                    <div style="width: 100%;display: flex;flex-direction: column;">
                        <el-upload ref="logoUploadRef" class="logo-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleWebLogoSuccess" :before-upload="beforeWebLogoUpload" :headers="uploadHeaders">
                            <img v-if="form.web_logo" :src="form.web_logo" class="logo-preview" />
                            <el-icon v-else class="logo-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <div class="upload-tip">只能上传jpg/png文件，且不超过2MB</div>
                    </div>
                </el-form-item>
                <el-form-item label="后台登录图片" prop="login_image">
                    <div style="width: 100%;display: flex;flex-direction: column;">
                        <el-upload ref="logoUploadRef" class="logo-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleLoginImageSuccess" :before-upload="beforeLoginImageUpload" :headers="uploadHeaders">
                            <img v-if="form.login_image" :src="form.login_image" class="logo-preview" />
                            <el-icon v-else class="logo-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <div class="upload-tip">只能上传jpg/png文件，且不超过2MB</div>
                    </div>
                </el-form-item>
                <el-form-item label="小程序名称" prop="shop_name">
                    <el-input v-model="form.shop_name" placeholder="请输入小程序名称" clearable />
                </el-form-item>
                <!-- 模板编号 -->
                <el-form-item label="小程序模版" prop="shop_template">
                    <el-input v-model="form.shop_template" placeholder="请输入小程序模版" clearable />
                </el-form-item>

                <!-- Logo上传 -->
                <el-form-item label="小程序logo" prop="shop_logo">
                    <div style="width: 100%;display: flex;flex-direction: column;">
                        <el-upload ref="logoUploadRef" class="logo-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleLogoSuccess" :before-upload="beforeLogoUpload" :headers="uploadHeaders">
                            <img v-if="form.shop_logo" :src="form.shop_logo" class="logo-preview" />
                            <el-icon v-else class="logo-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <div class="upload-tip">只能上传jpg/png文件，且不超过2MB</div>
                    </div>
                </el-form-item>

                <!-- 首页背景图 -->
                <el-form-item label="首页背景图" prop="shop_home_logo">
                    <div style="width: 100%;display: flex;flex-direction: column;">
                        <el-upload ref="bgUploadRef" class="bg-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleBgSuccess" :before-upload="beforeBgUpload" :headers="uploadHeaders">
                            <img v-if="form.shop_home_logo" :src="form.shop_home_logo" class="bg-preview" />
                            <el-icon v-else class="bg-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <div class="upload-tip">只能上传jpg/png文件，且不超过5MB</div>
                    </div>
                </el-form-item>

                <!-- 开屏页动画 -->
                <el-form-item label="开屏页动画" prop="shop_start_logo">
                    <div style="width: 100%;display: flex;flex-direction: column;">
                        <material-picker v-model="form.shop_start_logo" :limit="1" type="video"/>
                        <!-- <el-upload ref="splashUploadRef" class="splash-uploader" :action="uploadUrlVideo" :show-file-list="false"
                            :on-success="handleSplashSuccess" :before-upload="beforeSplashUpload" :headers="uploadHeaders">
                            <div v-if="form.shop_start_logo" class="splash-preview">
                                <video v-if="isVideo(form.shop_start_logo)" :src="form.shop_start_logo" controls
                                    class="media-preview" />
                                <img v-else :src="form.shop_start_logo" class="media-preview" />
                            </div>
                            <el-icon v-else class="splash-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload> -->
                        <div class="upload-tip">支持上传图片(jpg/png)或视频(mp4)文件，不超过10MB</div>
                    </div>
                    
                </el-form-item>

                <!-- 操作按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="loading">
                        保存配置
                    </el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { saveWebsiteConfig, getWebsiteConfig, type TemplateConfigData } from '@/api/template_config'

// 表单引用
const formRef = ref<FormInstance>()
const logoUploadRef = ref()
const bgUploadRef = ref()
const splashUploadRef = ref()

// 加载状态
const loading = ref(false)

// 上传配置
const uploadUrl = import.meta.env.VITE_APP_BASE_URL + 'api/upload/image'
const uploadUrlVideo = import.meta.env.VITE_APP_BASE_URL + 'api/upload/video'
const uploadHeaders = {
    Authorization: 'Bearer ' + localStorage.getItem('token')
}

// 表单数据
const form = reactive({
    name: '',
    web_logo: '',
    login_image: '',
    web_favicon: '',
    shop_name: '',
    shop_template: '',
    shop_logo: '',
    shop_home_logo: '',
    shop_start_logo: ''
})

// 表单验证规则
const rules: FormRules = {
    name: [
        { required: true, message: '请输入网站名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    web_logo: [
        { required: true, message: '请上传网站名称', trigger: 'change' }
    ],
    web_favicon: [
        { required: true, message: '请上传网站favicon', trigger: 'change' }
    ],
    login_image: [
        { required: true, message: '请上传后台登录图片', trigger: 'change' }
    ],
    shop_name: [
        { required: true, message: '请输入小程序名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    shop_template: [
        { required: true, message: '请输入小程序模版', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    shop_logo: [
        { required: true, message: '请上传小程序logo', trigger: 'change' }
    ],
    shop_home_logo: [
        { required: true, message: '请上传首页背景图', trigger: 'change' }
    ],
    shop_start_logo: [
        { required: true, message: '请上传开屏页动画', trigger: 'change' }
    ]
}

// 判断是否为视频文件
const isVideo = (url: string): boolean => {
    return url.toLowerCase().includes('.mp4') || url.toLowerCase().includes('video')
}

// 网站favicon上传成功回调
const handleWebFaviconSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.web_favicon = response.data.uri
        ElMessage.success('网站favicon上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 网站favicon上传前验证
const beforeWebFaviconUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isJPGOrPNG) {
        ElMessage.error('网站favicon只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('网站favicon大小不能超过 2MB!')
        return false
    }
    return true
}
// 后台登录图片上传成功回调
const handleLoginImageSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.login_image = response.data.uri
        ElMessage.success('后台登录图片上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 后台登录图片上传前验证
const beforeLoginImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isJPGOrPNG) {
        ElMessage.error('后台登录图片只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('后台登录图片大小不能超过 2MB!')
        return false
    }
    return true
}
// 网站名称上传成功回调
const handleWebLogoSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.web_logo = response.data.uri
        ElMessage.success('网站logo上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 网站名称上传前验证
const beforeWebLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isJPGOrPNG) {
        ElMessage.error('Logo只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('Logo大小不能超过 2MB!')
        return false
    }
    return true
}

// Logo上传前验证
const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isJPGOrPNG) {
        ElMessage.error('Logo只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('Logo大小不能超过 2MB!')
        return false
    }
    return true
}
// Logo上传成功回调
const handleLogoSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.shop_logo = response.data.uri
        ElMessage.success('Logo上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 背景图上传前验证
const beforeBgUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt5M = rawFile.size / 1024 / 1024 < 5

    if (!isJPGOrPNG) {
        ElMessage.error('背景图只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('背景图大小不能超过 5MB!')
        return false
    }
    return true
}

// 背景图上传成功回调
const handleBgSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.shop_home_logo = response.data.uri
        ElMessage.success('背景图上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 开屏页动画上传前验证
const beforeSplashUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isVideo = rawFile.type === 'video/mp4'
    const isLt10M = rawFile.size / 1024 / 1024 < 10

    if (!isImage && !isVideo) {
        ElMessage.error('开屏页动画只能是 JPG/PNG/MP4 格式!')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB!')
        return false
    }
    return true
}

// 开屏页动画上传成功回调
const handleSplashSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.shop_start_logo = response.data.uri
        ElMessage.success('开屏页动画上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true

        // 调用API保存配置
        const response = await saveWebsiteConfig(form as TemplateConfigData)
        console.log('response', response)
        ElMessage.success('配置保存成功')
        loading.value = false
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请重试')
        loading.value = false
    }
}

// 加载配置数据
const loadTemplateConfig = async () => {
    try {
        const response = await getWebsiteConfig()
        // const config = response.data.list[0]
        form.name = response.name || ''
        form.web_favicon = response.web_favicon || ''
        form.web_logo = response.web_logo || ''
        form.login_image = response.login_image || ''
        form.shop_name = response.shop_name || ''
        form.shop_template = response.shop_template || ''
        form.shop_logo = response.shop_logo || ''
        form.shop_home_logo = response.shop_home_logo || ''
        form.shop_start_logo = response.shop_start_logo || ''
    } catch (error) {
        console.error('加载配置失败:', error)
    }
}

// 重置表单
const resetForm = () => {
    ElMessageBox.confirm('确定要重置表单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        formRef.value?.resetFields()
        form.name = ''
        form.web_favicon = ''
        form.web_logo = ''
        form.login_image = ''
        form.shop_name = ''
        form.shop_template = ''
        form.shop_logo = ''
        form.shop_home_logo = ''
        form.shop_start_logo = ''
        ElMessage.success('表单已重置')
    })
}

// 组件挂载时加载配置
onMounted(() => {
    loadTemplateConfig()
})
</script>

<style scoped>
.template-config {
    padding: 20px;
}

.box-card {
    max-width: 800px;
    margin: 0 auto;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
}

.template-form {
    margin-top: 20px;
}

/* Logo上传样式 */
:deep(.logo-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.logo-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.logo-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
}

:deep(.logo-preview) {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* 背景图上传样式 */
:deep(.bg-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.bg-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.bg-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
}

:deep(.bg-preview) {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 开屏页动画上传样式 */
:deep(.splash-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.splash-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.splash-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
}

:deep(.splash-preview) {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.media-preview {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
}
</style>